import { TreeService } from '@service/tree.service';
import { LoginService } from '@service/login.service';
/* 配置路由守卫 */
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivateChild {

	constructor(
		private loginService: LoginService,
		private router: Router
	) { }
	canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
		const url: string = state.url;
		return this.checkLogin(url);
	}

	checkLogin(url): Observable<boolean> | Promise<boolean> | boolean {
		// const userInfo = this.loginService.getUserInfo();
		const token = this.loginService.getToken();
		const isHome = url.includes('/home');
		if (token) {
			return  isHome ? true : this.isAuthMenu(url);
		} else {
			this.router.navigate(['/login'], { queryParams: { redirectUrl: url } });
			return false;
		}
	}



	isAuthMenu(url: string) {
		const menuTree = this.loginService.getMenu();
		if (menuTree) {
			const menuUrls = this.getMenuUrl(menuTree, []);
			const menu = menuUrls.find(it => it.includes(url));
			if (menu) {
				return true;
			}else {
				this.router.navigate(['/exception/403']);
				return false;
			}
		} else {
			this.router.navigate(['/page/home']);
			return true;
		}
	}

	getMenuUrl(menuTree, result: string[]){
		menuTree.forEach(item => {
			if (item?.resUrl) {
				result.push(item?.resUrl);
			}
			if (item?.nodes?.length) {
				return this.getMenuUrl(item?.nodes, result);
			}
		});
		return result;
	}
}
